//医嘱关联过敏源
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Col } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import '../style/childStyle.less';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;

class OLDoseConversionUnit extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      allergens: [],
      selectData: {}, // 下拉框数据
      tableData: [], // 列表数据
      total: 0,
      page: 1,
      pageSize: 10,
      rowData: {}, // 编辑回显数据
      user: userData,
      medID: '',
    };
    this.columns = [
      {
        key: 1,
        title: '序号',
        dataIndex: 'key',
        align: "center",
        width: 50,
        render: (text, record, index) => {
          return this.state.tableData.findIndex((value, index) => {
            return value === record;
          }) + 1;
        }
      },
      {
        key: 2,
        title: '过敏源类型',
        dataIndex: 'allergyTypeDesc',
        align: "center",
        width: 150
      },
      {
        key: 3,
        title: '过敏源',
        dataIndex: 'allergensDesc',
        align: "center",
        width: 150
      },
      {
        key: 4,
        title: '生效日期',
        dataIndex: 'startDate',
        align: "center",
        width: 80
      },
      {
        key: 5,
        title: '失效日期',
        dataIndex: 'stopDate',
        align: "center",
        width: 80
      },
      {
        title: '操作',
        key: 7,
        align: "center",
        width: 80,
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            {/* 分割线 */}
            <Divider type="vertical" />
            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          </span>
        ),
      }
    ];
  }

  componentDidMount() {
    this.getSelectData();
    if ((this.props.medData && this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
      this.setState({ medID: this.props.medData.medID }, () => {
        this.handleQuery();
      })
    } else {
      this.child.handleLoading();
    }
  }

  componentWillReceiveProps(nextProps) {
    if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
      this.setState({ medID: nextProps.medData.medID }, () => {
        this.handleQuery();
        this.resetFields();
      })
    }
  }

  // 调用子组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }

  // 获取下拉框数据
  getSelectData = () => {
    let data = {
      params: [{
      }]
    }
    $http.post('urlS', this, {
      code: "03010056",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          this.setState({ selectData: { ...this.state.selectData, ...{ allergyType: res.result.Data } } });
        }
      }
    })
    $http.post('urlS', this, {
      code: "03010057",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          this.setState({ selectData: { ...this.state.selectData, ...{ allergens: res.result.Data } } });
        }
      }
    })
  }

  // 请求列表数据
  getTableData() {
    let { page, pageSize, medID } = this.state;
    let data = {
      params: [{
        medItemID: medID // 医嘱项id
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: "Describe",
        sortOrder: "asc"
      }]
    }
    $http.post('urlS', this, {
      code: "03010052",
      data: data,
      success: function (res) {
        if (+res.errorCode == 0 && res.result) {
          this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        } else {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        }
      },
      error: function () {
        this.setState({ tableData: [], total: 0 }, () => {
          // 数据加载成功关闭loading
          this.child.handleLoading();
        })
      }
    })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, pageSize: 10 }, () => {
      this.getTableData();
    })
  }


  // 保存
  handleSave = () => {
    const { rowData, user, medID } = this.state;
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      let data = {
        params: []
      };

      let obj = {};
      obj.linkID = rowData && rowData.linkID ? rowData.linkID : undefined;
      obj.medItemID = medID; // 医嘱项id
      obj.allergyTypeID = values.allergyTypeID || '';
      obj.allergensID = values.allergensID || '';;
      obj.startDate = values.startDate ? moment(values.startDate).format("YYYY-MM-DD") : '';
      obj.stopDate = values.stopDate ? moment(values.stopDate).format("YYYY-MM-DD") : '';
      obj.updateUserID = user.userID ? user.userID : '';
      data.params.push(obj);
      if (rowData.linkID) {
        $http.post('urlADS', this, {
          code: '03010054',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success('编辑成功');
              this.handleQuery();
              this.resetFields();
            }
          }
        })
      } else {
        $http.post('urlADS', this, {
          code: '03010055',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success('新增成功');
              this.handleQuery();
              this.resetFields();
            }
          }
        })
      }
    })
  }

  // 重置
  resetFields = () => {
    this.props.form.resetFields(); //清空所有
    this.setState({
      rowData: {}
    })
  }

  // 编辑
  handleCompile = record => {
    this.resetFields();
    this.setState({ rowData: record });
    this.setAllergyType(record.allergyTypeID);
  }

  // 删除
  handleDelete = record => {
    let data = {
      params: [{
        linkID: record.linkID,
      }]
    }
    $http.post('urlADS', this, {
      code: '03010053',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          // 刷新列表数据
          this.getTableData();
        }
      }
    })
  }

  onAllergyType = (value) => {
    // 过敏源
    const { selectData } = this.state;
    let allergens = [];
    selectData.allergens && selectData.allergens.map((item, index) => {
      if (value == item.typeID) {
        allergens.push(item)
      }
    })
    //console.log(allergens);
    this.setState({ allergens: allergens });
    this.props.form.setFieldsValue({ allergensID: undefined });
  }
  setAllergyType = (value) => {
    // 过敏源
    const { selectData } = this.state;
    let allergens = [];
    selectData.allergens && selectData.allergens.map((item, index) => {
      if (value == item.typeID) {
        allergens.push(item)
      }
    })
    //console.log(allergens);
    this.setState({ allergens: allergens });
  }
  compilePage = (page, pageSize) => {
    this.setState({
      page,
      pageSize,
    }, () => {
      this.getTableData()
    })

  }
  render() {
    const { selectData, tableData, total, page, rowData, allergens } = this.state;

    const { getFieldDecorator } = this.props.form;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total: total,
      // 当前页数
      page: page,
      // 表格的宽度
      x: 900,
      y: 360,
      TableClassName: "medAll",
      height: '400px'
    };

    const formLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    }

    // 过敏源类型
    let allergyTypeOpt = [];
    selectData.allergyType && selectData.allergyType.map((item, index) => {
      allergyTypeOpt.push(<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    });

    let allergensOpt = [];
    allergens && allergens.map((item, index) => {
      allergensOpt.push(<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    });

    return (
      <div>
        <Form layout={'horizontal'}>
          <Row>
            <Col span={5}>
              <Form.Item label="过敏源类型" {...formLayout}>
                {getFieldDecorator('allergyTypeID', {
                  initialValue: rowData.allergyTypeID ? rowData.allergyTypeID : undefined,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Select showSearch optionFilterProp="seatchprop" onChange={this.onAllergyType} allowClear style={{ width: '100%' }} placeholder="请选择">
                    {allergyTypeOpt}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label="过敏源" {...formLayout}>
                {getFieldDecorator('allergensID', {
                  initialValue: rowData.allergensID ? rowData.allergensID : undefined,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }} placeholder="请选择">
                    {allergensOpt}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label='生效日期' {...formLayout}>
                {getFieldDecorator('startDate', {
                  initialValue: rowData && rowData.startDate ? moment(rowData.startDate, "YYYY-MM-DD") : moment(),
                  rules: [{ required: false, message: '' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'请选择生效日期'} disabledDate={(curDate) => {
                    return curDate && curDate > moment().endOf('day');
                  }} />
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label='失效日期' {...formLayout}>
                {getFieldDecorator('stopDate', {
                  initialValue: rowData && rowData.stopDate ? moment(rowData.stopDate, "YYYY-MM-DD") : undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'请选择失效日期'} disabledDate={(curDate) => {
                    return curDate && curDate < moment().startOf('day');
                  }} />
                )}
              </Form.Item>
            </Col>
            <Col span={4}>
              <Button style={{ margin: '3px 10px 0 10px' }} type="primary" onClick={this.handleSave}>{rowData.linkID ? '修改' : '保存'}</Button>
              <span style={{ display: 'inline-block', marginTop: '4px' }}>
                <Button onClick={this.resetFields}>清空</Button>
              </span>
            </Col>
          </Row>
        </Form>
        <div>
          {/* <div style={{background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700'}}>
                        已添加转换单位
                        <span style={{float: 'right', fontWeight: '100'}}>
                            <Select value={hosp} onChange={this.handleHospID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{width: '200px', marginRight: '8px'}} placeholder="根据医院过滤数据">
                                {hospOption}
                            </Select>
                            <Select value={doseUnitID} onChange={this.handledoseUnitID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{width: '100px', marginRight: '8px'}} placeholder="等效单位">
                                {unitOption}
                            </Select>
                        </span>
                    </div> */}
          <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
        </div>
      </div>
    )
  }
};
const OLDoseConversionUnitForm = Form.create()(OLDoseConversionUnit);
export default OLDoseConversionUnitForm;